package com.qys.livesMall.anchor.controller.sys;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.qys.livesMall.anchor.enums.AnchorMessageEnum;
import com.qys.livesMall.anchor.mapper.LivesRoomAdminMapper;
import com.qys.livesMall.anchor.model.dto.EditAnchorDTO;
import com.qys.livesMall.anchor.model.dto.H2AnchorDTO;
import com.qys.livesMall.anchor.model.entity.H2Anchor;
import com.qys.livesMall.anchor.model.entity.H2AnchorApply;
import com.qys.livesMall.anchor.model.vo.AnchorStatisticsVO;
import com.qys.livesMall.anchor.model.vo.H2AnchorVO;
import com.qys.livesMall.anchor.service.H2AnchorApplyService;
import com.qys.livesMall.anchor.service.H2AnchorService;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.result.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 主播表(H2Anchor)表控制层
 *
 * @author makejava
 * @since 2023-06-17 09:35:51
 */
@RestController
@RequestMapping("/sys/anchor")
@Tag(name = "App-主播后台管理", description = "App-主播后台管理")
public class H2AnchorController {

    /**
     * 服务对象
     */
    @Resource
    private H2AnchorService h2AnchorService;
    @Resource
    private H2AnchorApplyService applyService;
    @Resource
    private H2AppUserMapper appUserMapper;
    @Resource
    private LivesRoomAdminMapper adminMapper;

    /**
     * 分页查询所有数据
     *
     * @param dto 分页对象
     * @return 所有数据
     */
    @PostMapping("/getAll")
    @Operation(summary = "查询主播列表")
    public R<IPage<H2AnchorVO>> getAll(@RequestBody H2AnchorDTO dto) {
        LambdaQueryWrapper<H2Anchor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(H2Anchor::getIsDelete,0);
        wrapper.eq(StringUtils.isNotEmpty(dto.getAnchorName()),H2Anchor::getAnchorName,dto.getAnchorName());
        wrapper.eq(StringUtils.isNotEmpty(dto.getUserName()),H2Anchor::getUserName,dto.getUserName());
        wrapper.eq(null != dto.getApplyStatus(),H2Anchor::getApplyStatus,dto.getApplyStatus());
        wrapper.orderByDesc(H2Anchor::getCreateTime);

        IPage<H2AnchorVO> page = h2AnchorService.page(new Page<>(dto.getPageNum(), dto.getPageSize()), wrapper).convert(e -> {
            H2AnchorVO anchorVO = new H2AnchorVO();
            BeanUtils.copyProperties(e, anchorVO);
            anchorVO.setSalesQuota(e.getSalesQuota().toString());
            H2AppUser appUser = appUserMapper.selectById(anchorVO.getUserId());
            //主播用户信息
            if(appUser != null){
                anchorVO.setUserName(appUser.getUserName());
                anchorVO.setUserRandomId(appUser.getUserRandomId());
            }
            //主播带货信息
            H2AnchorVO sellingInformation =  h2AnchorService.sellingInformation(anchorVO.getId());
            anchorVO.setSalesVolume(Optional.ofNullable(sellingInformation.getSalesVolume()).orElse(0));
            anchorVO.setSalesQuota(Optional.ofNullable(sellingInformation.getSalesQuota()).orElse("0.0000"));
            anchorVO.setOrderNumber(Optional.ofNullable(sellingInformation.getOrderNumber()).orElse(0));
            return anchorVO;
        });
        return R.ok(page);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/getById")
    @Operation(summary = "通过主键ID查询单条数据")
    public R<H2AnchorVO> getById(@RequestParam String id) {
        H2Anchor h2Anchor = this.h2AnchorService.getById(id);
        if(null == h2Anchor){
            throw new QysException(AnchorMessageEnum.NO_DATA);
        }
        H2AnchorVO anchorVO = new H2AnchorVO();
        BeanUtils.copyProperties(h2Anchor,anchorVO);
        //主播带货信息
        H2AnchorVO sellingInformation =  h2AnchorService.sellingInformation(anchorVO.getId());
        anchorVO.setSalesVolume(Optional.ofNullable(sellingInformation.getSalesVolume()).orElse(0));
        anchorVO.setSalesQuota(Optional.ofNullable(sellingInformation.getSalesQuota()).orElse("0.0000"));
        anchorVO.setOrderNumber(Optional.ofNullable(sellingInformation.getOrderNumber()).orElse(0));
        return R.ok(anchorVO);
    }

    /**
     * 新增数据
     *
     * @param h2Anchor 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody H2Anchor h2Anchor) {
        return R.ok(this.h2AnchorService.save(h2Anchor));
    }

    /**
     * 修改主播
     *
     * @param dto 修改主播实体对象
     * @return 修改结果
     */
    @PostMapping("/update")
    @Operation(summary = "修改主播")
    public R update(@RequestBody EditAnchorDTO dto) {
        H2Anchor anchor = new H2Anchor();
        anchor.setId(Long.valueOf(dto.getId()));
        anchor.setAnchorName(dto.getAnchorName());
        anchor.setFansNumber(dto.getFansNumber());
        anchor.setSalesVolume(dto.getSalesVolume());
        anchor.setSalesQuota(new BigDecimal(dto.getSalesQuota()));
        anchor.setOrderNumber(dto.getOrderNumber());
        anchor.setPhone(dto.getPhone());
        this.h2AnchorService.updateById(anchor);
        return R.ok();
    }

    /**
     * 冻结/解冻主播
     *
     * @param id 主播ID
     * @return 修改结果
     */
    @GetMapping("/frozenAnchor")
    @Operation(summary = "冻结/解冻主播")
    public R frozenAnchor(@RequestParam String id) {
        H2Anchor anchorServiceById = h2AnchorService.getById(id);
        if(null==anchorServiceById){
            throw new QysException(AnchorMessageEnum.NO_DATA);
        }

        H2Anchor anchor = new H2Anchor();
        anchor.setId(Long.parseLong(id));
        anchor.setAnchorStatus(1 == anchorServiceById.getAnchorStatus() ? 0 : 1);
        return R.ok(this.h2AnchorService.updateById(anchor));
    }

    /**
     * 删除主播
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @PostMapping("/delete")
    @Operation(summary = "删除主播")
    public R delete(@RequestBody List<String> idList) {
        idList.forEach(e->{
            H2Anchor h2Anchor = new H2Anchor();
            h2Anchor.setId(Long.valueOf(e));
            h2Anchor.setIsDelete(1);
            h2AnchorService.updateById(h2Anchor);
        });

        //删除主播的申请合同
        List<H2Anchor> anchors = h2AnchorService.list(Wrappers.<H2Anchor>lambdaQuery().in(H2Anchor::getId, idList));
        List<Long> list = anchors.stream().map(H2Anchor::getUserId).toList();
        applyService.remove(Wrappers.<H2AnchorApply>lambdaQuery().in(H2AnchorApply::getUserId, list));
        return R.ok();
    }

    @PostMapping("/settlementAllocation")
    @Operation(summary = "结算配置")
    public R<?> settlementAllocation(@RequestBody EditAnchorDTO dto){
        H2Anchor h2Anchor = new H2Anchor();
        h2Anchor.setId(Long.parseLong(dto.getId()));
        if(dto.getClearingForm() != null){
            if(!Lists.newArrayList(1, 2, 3).contains(dto.getClearingForm())){
                return R.fail("clearingForm error");
            } else {
                h2Anchor.setClearingForm(dto.getClearingForm());
            }
        }
        if(StringUtils.isNoneBlank(dto.getBasicSalary())){
            try {
                JSONObject.parseObject(dto.getBasicSalary());
            } catch (Exception e) {
                return R.fail("basicSalary error");
            }
            h2Anchor.setBasicSalary(dto.getBasicSalary());
        }
        if(dto.getCommissionRate() != null){
            if(dto.getCommissionRate().compareTo(BigDecimal.ZERO) > 0 && dto.getCommissionRate().compareTo(BigDecimal.ONE) <=0){
                h2Anchor.setCommissionRate(dto.getCommissionRate().abs());
            } else {
                return R.fail("commissionRate error");
            }
        }
        if(dto.getGiftRatio() != null){
            if(dto.getGiftRatio().compareTo(BigDecimal.ZERO) > 0 && dto.getGiftRatio().compareTo(BigDecimal.ONE) <=0){
                h2Anchor.setGiftRatio(dto.getGiftRatio().abs());
            } else {
                return R.fail("giftRatio error");
            }
        }
        h2AnchorService.updateById(h2Anchor);
        return R.ok();
    }

    @PostMapping("/taskAuthority/{id}")
    @Operation(summary = "开启/关闭带货任务权限")
    public R<?> taskAuthority(@PathVariable Long id){
        H2Anchor h2Anchor = h2AnchorService.getById(id);
        if(h2Anchor != null){
            Integer taskAuthority = h2Anchor.getTaskAuthority();
            h2Anchor.setTaskAuthority(0 == taskAuthority ? 1 : 0);
            h2AnchorService.updateById(h2Anchor);
        }
        return R.ok();
    }

    @PostMapping("/liveEntertainment/{id}")
    @Operation(summary = "开启/关闭带货娱乐直播权限")
    public R<?> liveEntertainment(@PathVariable Long id){
        H2Anchor h2Anchor = h2AnchorService.getById(id);
        if(h2Anchor != null){
            Integer liveEntertainment = h2Anchor.getLiveEntertainment();
            h2Anchor.setLiveEntertainment(0 == liveEntertainment ? 1 : 0);
            h2AnchorService.updateById(h2Anchor);
        }
        return R.ok();
    }

    @GetMapping("/inquireSettlementAllocation/{id}")
    @Operation(summary = "查询结算配置")
    public R<EditAnchorDTO> inquireSettlementAllocation(@PathVariable Long id) {
        H2Anchor h2Anchor = h2AnchorService.getById(id);
        EditAnchorDTO anchorDTO = null;
        if (h2Anchor != null) {
            anchorDTO = new EditAnchorDTO();
            anchorDTO.setClearingForm(h2Anchor.getClearingForm());
            anchorDTO.setBasicSalary(h2Anchor.getBasicSalary());
            anchorDTO.setCommissionRate(h2Anchor.getCommissionRate());
            anchorDTO.setGiftRatio(h2Anchor.getGiftRatio());
        }
        return R.ok(anchorDTO);
    }

    @GetMapping("/anchorStatistics")
    @Operation(summary = "主播数据统计")
    public R<AnchorStatisticsVO> anchorStatistics(){
        AnchorStatisticsVO anchorStatisticsVO = new AnchorStatisticsVO();
        LambdaQueryWrapper<H2Anchor> queryWrapper = Wrappers.<H2Anchor>lambdaQuery().eq(H2Anchor::getIsDelete, 0).eq(H2Anchor::getApplyStatus, 2);
        anchorStatisticsVO.setAnchorTotal((int)h2AnchorService.count(queryWrapper));
        anchorStatisticsVO.setNewToday((int)h2AnchorService.count(queryWrapper.gt(H2Anchor::getCreateTime, LocalDate.now().atStartOfDay())));
        return R.ok(anchorStatisticsVO);
    }


    @Operation(summary = "恢复直播开播前状态（仅供测试）")
    @GetMapping("/refreshStatus/{sessionId}")
    public R<?> refreshStatus(@PathVariable Long sessionId){
        adminMapper.refreshStatus(sessionId);
        return R.ok();
    }
}

